const Service = require('egg').Service;



/**
 * 接口管理
 */
class ApiCommonService extends Service {
	// 接口查询
	async queryApi(data) {
        const { ctx, app, service } = this;
        const { id, type, tableName } = data;
        // 如果有id,则根据id查找
        if (id !== undefined && id !== '') {
            return await app.mongo.findOne(tableName, {
               query: { _id: app.getObjectId(id) }
            })
        }
        // type返回数据类型接口，
        if (type !== undefined && type === 1) {
            return await app.mongo.findOne(tableName, {
               query: {}
            })
        }

        // 默认返回列表数据
		const res = await app.mongo.find(tableName, {
		})
		return res;
	}
	// 创建接口分类
	async createApi(data) {
		const { ctx, app } = this;
		const createTime = ctx.helper.getCurrentTime();
		// 从对应的表中插入数据
		const res = await app.mongo.insertOne(data.tableName, {
			doc: { createTime, ...data }
		});
		return res;
	}
	// 更新接口
    async updateApi(data) {
        const { ctx, app } = this;
        const _id = app.getObjectId(data._id);
        // 过滤出_id,不然更新会出错
        const newData = data.map(item => {
            delete item._id;
            return item;
        })
        const res = await app.mongo.findOneAndUpdate(data.tableName, {
            filter: { _id },
            update: {
                $set: { ...newData }
            }
        });
		return res;
    }
	// 删除数据
	async deleteApi(data) {
		const { ctx, app } = this;
		const _id = app.getObjectId(data._id);
		const res = await app.mongo.findOneAndDelete(data.tableName, {
			filter: { _id }
		});
		return res;
	}
}

module.exports = ApiCommonService;
